package com.stedu.config;

import com.stedu.interceptor.AdminInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * SpringMVC的配置类，代替SpringMVC的XML配置文件
 */
//开启SpringMVC
@EnableWebMvc
//配置SpringMVC的包扫描
@ComponentScan(basePackages = "com.stedu",
        useDefaultFilters = false,
        includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class))
public class WebConfig implements WebMvcConfigurer {
    //配置视图解析器
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        //配置视图的前缀
        viewResolver.setPrefix("/WEB-INF/");
        //配置视图的后缀
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        /**
         *    配置静态资源放行，DispatcherServlet将对静态资源的请求转发到Servlet容器中默认的Servlet上，
         *    而不是使用DispatcherServlet本身来处理此类请求
         *
         *  配置静态资源放行
         */
        configurer.enable();
    }

    //配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AdminInterceptor()) //添加拦截器
                .addPathPatterns("/admin/**"); //拦截器拦截的路径
    }
}
